package com.example.teacherservice.service;

import com.example.teacherservice.dto.StudentCourseDTO;
import com.example.teacherservice.entity.Course;
import com.example.teacherservice.repository.CourseRepository;
import com.example.teacherservice.repository.StuCourseRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public interface StudentCourseService {

    StuCourseRepository getStuCourseRepository();
    CourseRepository getCourseRepository();

    default Optional<Long> getStudentIdByUserId(Long userId) {
        return getStuCourseRepository().findStudentIdByUserId(userId);
    }

    default List<StudentCourseDTO> getCoursesByStudentId(Long studentId) {
        // 获取学生选课关系
        List<Long> courseIds = getStuCourseRepository().findCourseIdsByStudentId(studentId);

        // 获取课程详细信息
        List<Course> courses = getCourseRepository().findAllById(courseIds);

        // 转换为DTO
        return courses.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    default List<StudentCourseDTO> getCoursesByUserId(Long userId) {
        return getStudentIdByUserId(userId)
                .map(this::getCoursesByStudentId)
                .orElse(List.of());
    }

    private StudentCourseDTO convertToDTO(Course course) {
        StudentCourseDTO dto = new StudentCourseDTO();
        dto.setCourseId(course.getId());
        dto.setCouName(course.getCouName());
        dto.setCouIntroduction(course.getCouIntroduction());
        dto.setCouPic(course.getCouPic());
        dto.setCouPrice(course.getCouPrice());
        dto.setCouCollNum(course.getCouCollNum());
        dto.setClicks(course.getClicks());
        return dto;
    }

    default boolean hasCourse(Long studentId, Long courseId) {
        return getStuCourseRepository().existsByStuIdAndCourseId(studentId, courseId);
    }


}